//
//  YZCommunityLocationModel.m
//  VET
//
//  Created by YZ on 2018/7/11.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZMediaSourceManager.h"

@implementation YZMediaSourceManager

+ (void)saveImage:(UIImage *)image completionHandler:(YZMediaCompletionBlock)completion
{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status != PHAuthorizationStatusAuthorized)
        {
            NSDictionary *userInfo = @{ NSLocalizedDescriptionKey:@"没有访问权限"};
            NSError *error = [NSError errorWithDomain:@"" code:-101 userInfo:userInfo];
            if (completion) {
                completion(NO,error,nil);
            }
            return;
        }
        // 保存相片到相机胶卷
        __block  NSString *assetLocalIdentifier;
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            if (iOS9_OR_LATER) {
                NSData *data = UIImageJPEGRepresentation(image, 0.9);
                PHAssetResourceCreationOptions *options = [[PHAssetResourceCreationOptions alloc] init];
                options.shouldMoveFile = YES;
                PHAssetCreationRequest *request = [PHAssetCreationRequest creationRequestForAsset];
                assetLocalIdentifier = request.placeholderForCreatedAsset.localIdentifier;
                [request addResourceWithType:PHAssetResourceTypePhoto data:data options:options];
                request.creationDate = [NSDate date];
            } else {
                PHAssetChangeRequest *request = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
                assetLocalIdentifier = request.placeholderForCreatedAsset.localIdentifier;
                request.creationDate = [NSDate date];
            }
        } completionHandler:^(BOOL success, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (success && completion) {
                    PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetLocalIdentifier] options:nil].lastObject;
                    completion(success,error,asset);
                    completion(YES,error,asset);
                } else if (error) {
                    NSLog(@"保存照片出错:%@",error.localizedDescription);
                    if (completion) {
                        completion(NO,error,nil);
                    }
                }
            });
        }];
    }];
    
//        __block  NSString *assetLocalIdentifier;
//        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
//            assetLocalIdentifier = [PHAssetCreationRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
//        } completionHandler:^(BOOL success, NSError * _Nullable error) {
//            if (completion) {
//                PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetLocalIdentifier] options:nil].lastObject;
//                completion(success,error,asset);
//            }
//        }];
//    }];
}

+ (void)saveImage:(UIImage *)image toAlbum:(NSString *)albumName completionHandler:(YZMediaCompletionBlock)completion
{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status != PHAuthorizationStatusAuthorized)
        {
            NSDictionary *userInfo = @{ NSLocalizedDescriptionKey:@"没有访问权限"};
            NSError *error = [NSError errorWithDomain:@"" code:-101 userInfo:userInfo];
            if (completion) {
                completion(NO,error,nil);
            }
            return;
        }
        __block  NSString *assetLocalIdentifier;
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            //1.保存图片到相机胶卷中----创建图片的请求
            assetLocalIdentifier = [PHAssetCreationRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if (completion) {
                completion(success,error,nil);
            }
            if(success == NO){
                return ;
            }
            // 2.获得相簿
            PHAssetCollection *createdAssetCollection = [self createAssetCollectionWithAlbumName:albumName];
            if (createdAssetCollection == nil) {
                NSDictionary *userInfo = @{ NSLocalizedDescriptionKey:@"创建相簿失败"};
                NSError *error = [NSError errorWithDomain:@"" code:-101 userInfo:userInfo];
                if (completion) {
                    completion(NO,error,nil);
                }
                return;
            }
            
            // 3.将刚刚添加到"相机胶卷"中的图片到"自己创建相簿"中
            __block PHAsset *asset = nil;
            [[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
                //获得图片
                asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetLocalIdentifier] options:nil].lastObject;
                //添加图片到相簿中的请求
                PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:createdAssetCollection];
                // 添加图片到相簿
                [request addAssets:@[asset]];
            } completionHandler:^(BOOL success, NSError * _Nullable error) {
                if (completion) {
                    completion(success,error,asset);
                }
                if (error) {
                    NSLog(@"%@",error);
                }
            }];
        }];
    }];
}

+ (void)saveFile:(NSURL *)fileUrl completionHandler:(YZMediaCompletionBlock)completion
{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status != PHAuthorizationStatusAuthorized)
        {
            NSDictionary *userInfo = @{NSLocalizedDescriptionKey:@"没有访问权限"};
            NSError *error = [NSError errorWithDomain:@"" code:-101 userInfo:userInfo];
            if (completion) {
                completion(NO,error,nil);
            }
            return;
        }
        // 保存相片到相机胶卷
        __block  NSString *assetLocalIdentifier;
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            if (iOS9_OR_LATER) {
                PHAssetResourceCreationOptions *options = [[PHAssetResourceCreationOptions alloc] init];
                options.shouldMoveFile = YES;
                PHAssetCreationRequest *request = [PHAssetCreationRequest creationRequestForAsset];
                [request addResourceWithType:PHAssetResourceTypeVideo fileURL:fileUrl options:options];
                assetLocalIdentifier = request.placeholderForCreatedAsset.localIdentifier;
                request.creationDate = [NSDate date];
            } else {
                PHAssetChangeRequest *request = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:fileUrl];
                assetLocalIdentifier = request.placeholderForCreatedAsset.localIdentifier;
                request.creationDate = [NSDate date];
            }
        } completionHandler:^(BOOL success, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (success && completion) {
                    PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetLocalIdentifier] options:nil].lastObject;
                    completion(YES,error,asset);
                } else if (error) {
                    NSLog(@"保存视频出错:%@",error.localizedDescription);
                    if (completion) {
                        completion(NO,error,nil);
                    }
                }
            });
        }];
        
        // 保存相片到相机胶卷
//        __block  NSString *assetLocalIdentifier;
//        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
//            assetLocalIdentifier = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:fileUrl].placeholderForCreatedAsset.localIdentifier;
//        } completionHandler:^(BOOL success, NSError * _Nullable error) {
//            if (completion) {
//                PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetLocalIdentifier] options:nil].lastObject;
//                completion(success,error,asset);
//            }
//        }];
    }];
}

+ (void)saveFile:(NSURL *)fileUrl toAlbum:(NSString *)albumName completionHandler:(YZMediaCompletionBlock)completion
{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status != PHAuthorizationStatusAuthorized)
        {
            NSDictionary *userInfo = @{NSLocalizedDescriptionKey:@"没有访问权限"};
            NSError *error = [NSError errorWithDomain:@"" code:-101 userInfo:userInfo];
            if (completion) {
                completion(NO,error,nil);
            }
            return;
        }
        __block  NSString *assetLocalIdentifier;
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            assetLocalIdentifier = [PHAssetCreationRequest creationRequestForAssetFromVideoAtFileURL:fileUrl].placeholderForCreatedAsset.localIdentifier;
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if (completion) {
                completion(success,error,nil);
            }
            if(success == NO){
                return ;
            }
            // 2.获得相簿
            PHAssetCollection *createdAssetCollection = [self createAssetCollectionWithAlbumName:albumName];
            if (createdAssetCollection == nil) {
                NSDictionary *userInfo = @{ NSLocalizedDescriptionKey:@"创建相簿失败"};
                NSError *error = [NSError errorWithDomain:@"" code:-101 userInfo:userInfo];
                if (completion) {
                    completion(NO,error,nil);
                }
                return;
            }
            
            // 3.将刚刚添加到"相机胶卷"中的图片到"自己创建相簿"中
            __block PHAsset *asset = nil;
            [[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
                asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetLocalIdentifier] options:nil].lastObject;
                PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:createdAssetCollection];
                [request addAssets:@[asset]];
            } completionHandler:^(BOOL success, NSError * _Nullable error) {
                if (completion) {
                    completion(success,error,asset);
                }
            }];
        }];
    }];
}

// 获得相簿
+ (PHAssetCollection *)createAssetCollectionWithAlbumName:(NSString *)albumName
{
    //判断是否已存在
    PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection * assetCollection in assetCollections) {
        if ([assetCollection.localizedTitle isEqualToString:albumName]) {
            //说明已经有哪对象了
            return assetCollection;
        }
    }
    //创建新的相簿
    __block NSString *assetCollectionLocalIdentifier = nil;
    NSError *error = nil;
    //同步方法
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        // 创建相簿的请求
        assetCollectionLocalIdentifier = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:albumName].placeholderForCreatedAssetCollection.localIdentifier;
    } error:&error];
    if (error)return nil;
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[assetCollectionLocalIdentifier] options:nil].lastObject;
}

///**
// 保存视频缩略图
// 
// @param orientation 拍摄时的方向
// */
//- (void)saveVideoThumbnailToPhotoLibraryWithOrientation:(AVCaptureVideoOrientation)orientation
//{
//    
//    AVURLAsset *urlSet = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:self.currentVideoPath]];
//    
//    int totalSeconds = ceil([urlSet duration].value / [urlSet duration].timescale);
//    
//    AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlSet];
//    
//    imageGenerator.requestedTimeToleranceAfter = kCMTimeZero;
//    
//    imageGenerator.requestedTimeToleranceBefore = kCMTimeZero;
//    
//    //获取视频中间帧作为缩略图, 可自行更改
//    CMTime time = CMTimeMakeWithSeconds(totalSeconds / 2, 600);
//    
//    NSError *error = nil;
//    
//    CGImageRef cgimage = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:&error];
//    
//    NSLog(@"视频缩略图获取结果 :%d",!error);
//    
//    if (error) return;
//    
//    UIImageOrientation imageOrientation = UIImageOrientationUp;
//    
//    switch (orientation) {
//        case AVCaptureVideoOrientationLandscapeLeft:
//        {
//            imageOrientation = UIImageOrientationRight;
//        }
//            break;
//        case AVCaptureVideoOrientationLandscapeRight:
//        {
//            imageOrientation = UIImageOrientationRight;
//        }
//            break;
//        case AVCaptureVideoOrientationPortraitUpsideDown:
//        {
//            imageOrientation  = UIImageOrientationRight;
//        }
//            break;
//        case AVCaptureVideoOrientationPortrait:
//        {
//            imageOrientation = UIImageOrientationRight;
//        }
//            break;
//    }
//    
//    UIImage *resultImage = [UIImage imageWithCGImage:cgimage scale:1 orientation:imageOrientation];
//    
//    NSLog(@"imageOrientation %ld",resultImage.imageOrientation);
//    
//    NSData *imgData = UIImageJPEGRepresentation(resultImage, 1.0);
//    
//    BOOL imageWriteResult = [imgData writeToFile:self.currentThumbnailPath atomically: YES];
//    
//    NSLog(@"缩略图写入结果:%d",imageWriteResult);
//    
//    CGImageRelease(cgimage);
//}

@end
